package com.mantru.iotpot.setting;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.mantru.iotpot.R;

import org.json.JSONObject;

import java.util.UUID;

public class QRCodeActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 100;
    private ImageView qrCodeImageView;
    private String app_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);
        qrCodeImageView = findViewById(R.id.qr_code_image_view);
        app_id = getIntent().getStringExtra("app_id");
        checkPermissionsAndGenerateQR();
        findViewById(R.id.qr_code_back).setOnClickListener(v -> finish());
    }

    private void checkPermissionsAndGenerateQR() {
        if (needPhoneStatePermission()) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_PHONE_STATE},
                        PERMISSION_REQUEST_CODE);
            } else {
                generateSafeQRCode();
            }
        } else {
            generateSafeQRCode();
        }
    }

    private boolean needPhoneStatePermission() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.Q;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                generateSafeQRCode();
            } else {
                showFallbackQRCode();
            }
        }
    }

    private void generateSafeQRCode() {
//        String deviceIdentifier = getDeviceIdentifier();
        String qrData = createJsonData(app_id, "3", "catering");
        generateQRImage(qrData);
    }

    private String createJsonData(String device_id, String device_type, String product_type) {
        JSONObject json = new JSONObject();
        try {
            json.put("device_id", device_id);
            json.put("device_type", device_type);
            json.put("product_type", product_type);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

//    private String getDeviceIdentifier() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            return getAndroidId();
//        }
//
//        try {
//            TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//            if (tm != null && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
//                    == PackageManager.PERMISSION_GRANTED) {
//                String imei = tm.getDeviceId();
//                return imei != null ? imei : getAndroidId();
//            }
//        } catch (SecurityException e) {
//            e.printStackTrace();
//        }
//        return getAndroidId();
//    }

    private String getAndroidId() {
        String androidId = Settings.Secure.getString(
                getContentResolver(),
                Settings.Secure.ANDROID_ID
        );
        return androidId != null ? androidId : generateFallbackId();
    }

    private String generateFallbackId() {
        SharedPreferences prefs = getSharedPreferences("device_prefs", MODE_PRIVATE);
        String storedId = prefs.getString("device_id", null);
        if (storedId == null) {
            storedId = UUID.randomUUID().toString();
            prefs.edit().putString("device_id", storedId).apply();
        }
        return storedId;
    }

    private void showFallbackQRCode() {
        Toast.makeText(this, "使用备用标识生成二维码", Toast.LENGTH_SHORT).show();
        generateSafeQRCode();
    }

    private void generateQRImage(String data) {
        try {
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, 512, 512);
            BarcodeEncoder encoder = new BarcodeEncoder();
            Bitmap bitmap = encoder.createBitmap(bitMatrix);
            qrCodeImageView.setImageBitmap(bitmap);
        } catch (WriterException e) {
            Toast.makeText(this, "二维码生成失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}